package com.ruoyi.project.ins.utils;

import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;

public class UserAccountUtils {
    private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final String LOWER_ALPHA = "abcdefghijklmnopqrstuvwxyz";
    private static final SecureRandom RANDOM = new SecureRandom();
    private static final int MAX_USERNAME_LENGTH = 30;

    // 可选真实昵称词库（可扩展）
    private static final List<String> PREFIXES = Arrays.asList(
            "luna", "john", "emma", "cat", "mario", "sophie", "tony", "david", "angel", "sunny", "mia", "nova", "leo"
    );

    // 生成主方法
    public static String generateUsername() {
        String prefix = getRandomPrefix();
        long micros = Instant.now().toEpochMilli() * 1000 + (System.nanoTime() % 1000);
        String encodedTime = encodeBase62(micros);
        String salt = randomAlphaNumeric(4);  // 可调长度

        String username = prefix + "_" + encodedTime + salt;

        // 截断至 Instagram 最大长度限制
        return username.length() > MAX_USERNAME_LENGTH
                ? username.substring(0, MAX_USERNAME_LENGTH)
                : username;
    }

    // 获取随机前缀（从词库或随机字母中选）
    private static String getRandomPrefix() {
        if (RANDOM.nextBoolean()) {
            return PREFIXES.get(RANDOM.nextInt(PREFIXES.size()));
        } else {
            return randomLowerAlpha(4 + RANDOM.nextInt(3)); // 长度 4-6
        }
    }

    // 随机 a-z 字母串
    private static String randomLowerAlpha(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(LOWER_ALPHA.charAt(RANDOM.nextInt(LOWER_ALPHA.length())));
        }
        return sb.toString();
    }

    // 随机 a-zA-Z0-9 串
    private static String randomAlphaNumeric(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));
        }
        return sb.toString();
    }

    // Base62 编码
    private static String encodeBase62(long value) {
        StringBuilder sb = new StringBuilder();
        do {
            int index = (int) (value % 62);
            sb.append(ALPHABET.charAt(index));
            value /= 62;
        } while (value > 0);
        return sb.reverse().toString();
    }
}
